package com.zapi.notification.service.impl;

import com.zapi.notification.config.NotificationConfig;
import com.zapi.notification.controller.WebSocketController;
import com.zapi.notification.entity.Message;
import com.zapi.notification.service.MessageService;
import com.zapi.notification.service.MessageTemplateService;
import com.zapi.notification.service.NotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 通知服务实现类
 */
@Service
public class NotificationServiceImpl implements NotificationService {

    @Autowired
    private NotificationConfig notificationConfig;

    @Autowired
    private MessageService messageService;

    @Autowired
    private MessageTemplateService messageTemplateService;

    @Autowired
    private WebSocketController webSocketController;

    @Override
    public boolean sendStationMessage(Message message) {
        if (!notificationConfig.getStationMessage().isEnabled()) {
            return false;
        }
        
        // 检查消息内容长度
        if (message.getContent() != null && 
            message.getContent().length() > notificationConfig.getStationMessage().getMaxContentLength()) {
            throw new RuntimeException("消息内容超过最大长度限制");
        }
        
        return messageService.sendMessage(message);
    }

    @Override
    public int sendBatchStationMessages(List<Message> messages) {
        if (!notificationConfig.getStationMessage().isEnabled()) {
            return 0;
        }
        
        // 检查消息内容长度
        for (Message message : messages) {
            if (message.getContent() != null && 
                message.getContent().length() > notificationConfig.getStationMessage().getMaxContentLength()) {
                throw new RuntimeException("消息内容超过最大长度限制: " + message.getTitle());
            }
        }
        
        return messageService.sendBatchMessages(messages);
    }

    @Override
    public boolean sendRealTimeMessage(Long userId, String message) {
        if (!notificationConfig.getRealTimeMessage().isEnabled()) {
            return false;
        }
        
        try {
            webSocketController.pushSystemNotification(userId, message);
            return true;
        } catch (Exception e) {
            // 记录日志但不抛出异常
            return false;
        }
    }

    @Override
    public int sendBatchRealTimeMessages(List<Long> userIds, String message) {
        if (!notificationConfig.getRealTimeMessage().isEnabled()) {
            return 0;
        }
        
        int successCount = 0;
        for (Long userId : userIds) {
            if (sendRealTimeMessage(userId, message)) {
                successCount++;
            }
        }
        
        return successCount;
    }

    @Override
    public boolean sendSms(String phoneNumber, String templateCode, Map<String, Object> params) {
        if (!notificationConfig.getSms().isEnabled()) {
            return false;
        }
        
        try {
            // 渲染短信模板
            String content = messageTemplateService.renderTemplate(templateCode, params);
            
            // 根据配置的短信服务商发送短信
            String provider = notificationConfig.getSms().getProvider();
            if ("ALIYUN".equals(provider)) {
                return sendAliyunSms(phoneNumber, content);
            } else if ("TENCENT".equals(provider)) {
                return sendTencentSms(phoneNumber, content);
            } else {
                throw new RuntimeException("不支持的短信服务商: " + provider);
            }
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public int sendBatchSms(List<String> phoneNumbers, String templateCode, Map<String, Object> params) {
        if (!notificationConfig.getSms().isEnabled()) {
            return 0;
        }
        
        int successCount = 0;
        for (String phoneNumber : phoneNumbers) {
            if (sendSms(phoneNumber, templateCode, params)) {
                successCount++;
            }
        }
        
        return successCount;
    }

    @Override
    public boolean sendEmail(String to, String subject, String content) {
        if (!notificationConfig.getEmail().isEnabled()) {
            return false;
        }
        
        try {
            // 这里应该集成邮件发送服务，如JavaMailSender
            // 暂时返回true表示发送成功
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public int sendBatchEmails(List<String> toList, String subject, String content) {
        if (!notificationConfig.getEmail().isEnabled()) {
            return 0;
        }
        
        int successCount = 0;
        for (String to : toList) {
            if (sendEmail(to, subject, content)) {
                successCount++;
            }
        }
        
        return successCount;
    }

    @Override
    public boolean sendTemplateEmail(String to, String templateCode, Map<String, Object> params) {
        if (!notificationConfig.getEmail().isEnabled()) {
            return false;
        }
        
        try {
            // 渲染邮件模板
            String content = messageTemplateService.renderTemplate(templateCode, params);
            String subject = "系统通知"; // 可以从模板中获取或作为参数传入
            
            return sendEmail(to, subject, content);
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean broadcastSystemMessage(String message) {
        if (!notificationConfig.getRealTimeMessage().isEnabled()) {
            return false;
        }
        
        try {
            webSocketController.broadcastSystemMessage(message);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean sendToUserGroup(String groupId, String message) {
        if (!notificationConfig.getRealTimeMessage().isEnabled()) {
            return false;
        }
        
        try {
            webSocketController.sendToUserGroup(groupId, message);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 发送阿里云短信
     */
    private boolean sendAliyunSms(String phoneNumber, String content) {
        // 这里应该集成阿里云短信SDK
        // 暂时返回true表示发送成功
        return true;
    }

    /**
     * 发送腾讯云短信
     */
    private boolean sendTencentSms(String phoneNumber, String content) {
        // 这里应该集成腾讯云短信SDK
        // 暂时返回true表示发送成功
        return true;
    }
} 